from rest_framework import generics
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from django.http import JsonResponse
from django.db.models import Count,Max
from .models import Project,RequestsInfo,ScriptStep
from .serializer import ProjectSerializer
import json




# Create your views here.
class MyPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = 'page'

class ProjectListCreateView(generics.ListCreateAPIView):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

    def create(self, request, *args, **kwargs):
        # 从请求中获取项目名称
        project_name = request.data.get('projectName')

        # 数据校验
        if not project_name:
            return Response({"code": 400, "message": "Project name is required."})
        print(request.data)
        # 创建新的 Project 对象
        try:
            return super().create(request, *args, **kwargs)
        except ValidationError as e:
            print(e)
            return Response({"code": 400, })

class ProjectRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

    def perform_update(self, serializer):
        # 获取要更新的项目对象

        instance = serializer.instance
        print(instance)
        # 校验项目名称是否已经存在
        project_name = serializer.validated_data.get('projectName')
        print(project_name)
        if Project.objects.filter(projectName=project_name).exists():
            print("==============")
            return Response({"code":400,'message': '项目名称已经存在'})

        # 保存更新后的 Project 对象
        instance.projectName = project_name
        serializer.save()
        return Response({"code": 200, 'message': '修改成功'})
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"code":200,'message': '删除成功'})
